package com.leyou.cart.service;

import com.leyou.auth.pojo.UserInfo;
import com.leyou.cart.client.CollectClient;
import com.leyou.cart.client.GoodsClient;
import com.leyou.cart.filter.LoginInterceptor;
import com.leyou.cart.pojo.Cart;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.pojo.Attention;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.Spu;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private CollectClient collectClient;

    static final String KEY_PREFIX = "ly:cart:uid:";

    static final Logger logger = LoggerFactory.getLogger(CartService.class);

    //添加商品到购物车中
    public void addCart(Cart cart) {
        //获得用户信息
        UserInfo user = LoginInterceptor.getLoginUser();
        //获得该用户购物车的Key值
        String key = KEY_PREFIX + user.getId();
        //从redis中获得购物车的操作对象
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(key);

        //获得Cart中传递过来的数据
        Long skuId = cart.getSkuId();
        Integer num = cart.getNum();
        //判断该商品是否存在
        if (hashOps.hasKey(skuId.toString())) {
            //存在,数量相加
            String json = hashOps.get(skuId.toString()).toString();
            cart = JsonUtils.parse(json, Cart.class);
            cart.setNum(cart.getNum() + num);
        } else {
            //不存在
            //查询sku信息
            Sku sku = goodsClient.querySkuById(cart.getSkuId());
            //封装Cart
            cart.setUserId(user.getId());
            cart.setImage(StringUtils.isNotBlank(sku.getImages()) ? StringUtils.split(sku.getImages(), ",")[0] : "");
            cart.setPrice(sku.getPrice());
            cart.setTitle(sku.getTitle());
        }
        //将数据写入redis中
        hashOps.put(skuId.toString(), JsonUtils.serialize(cart));
    }

    //合并购物车
    public void mergeCart(List<Cart> carts) {
        for (Cart cart : carts) {
            this.addCart(cart);
        }
    }

    //查询购物车数据
    public List<Cart> queryCarts() {
        //获得登录用户信息
        UserInfo user = LoginInterceptor.getLoginUser();

        //判断redis中是否存在该用户的购物车信息
        String key = KEY_PREFIX + user.getId();
        if (!redisTemplate.hasKey(key)) {
            //不存在
            return null;
        }

        //存在
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(key);
        //获得该购物车中的数据
        List<Object> carts = hashOps.values();
        if (CollectionUtils.isEmpty(carts)) {
            return null;
        }

        //返回carts
        List<Cart> cartList = carts.stream().map(o -> JsonUtils.parse(o.toString(), Cart.class)).collect(Collectors.toList());
        for (Cart cart : cartList) {
            Long skuId = cart.getSkuId();
            Sku sku = goodsClient.querySkuById(skuId);
            Spu spu = goodsClient.querySpuById(sku.getSpuId());
            cart.setSaleable(spu.getSaleable());
            cart.setCurrentPrice(sku.getPrice());
        }

        return cartList;
    }

    //更新购物车中的数据
    public void updateNum(Long skuId, Integer num) {
        //获得用户信息
        UserInfo user = LoginInterceptor.getLoginUser();
        //获得该用户购物车的Key值
        String key = KEY_PREFIX + user.getId();


        //从redis中获得购物车的操作对象
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(key);

        //获得购物车数据
        String json = hashOps.get(skuId.toString()).toString();
        Cart cart = JsonUtils.parse(json, Cart.class);
        cart.setNum(num);

        //将数据写入redis中
        hashOps.put(skuId.toString(), JsonUtils.serialize(cart));
    }

    //删除购物车中数据
    public void deleteCart(String skuId) {
        //获得用户信息
        UserInfo user = LoginInterceptor.getLoginUser();
        //获得该用户购物车的Key值
        String key = KEY_PREFIX + user.getId();

        //从redis中获得购物车的操作对象
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(key);
        hashOps.delete(skuId);
    }
    // 单个添加商品到我的关注
    @Transactional(rollbackFor=Exception.class)
    public void addCollect(Cart cart) {
        // 获取登录用户信息
        UserInfo user = LoginInterceptor.getLoginUser();
        String key = KEY_PREFIX + user.getId();
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key);

        // 查询sku信息添加到收藏表
        Attention collect = new Attention();
        collect.setUserId(user.getId());
        collect.setSkuId(cart.getSkuId());
        collect.setImage(cart.getImage());
        collect.setOwnSpec(cart.getOwnSpec());
        collect.setPrice(cart.getPrice());
        collect.setTitle(cart.getTitle());

        this.collectClient.addCollect(collect);

        deleteCart(cart.getSkuId().toString());
    }
    // 添加我的关注
    @Transactional(rollbackFor=Exception.class)
    public void addCollectAll(List<Cart> carts) {
        for (Cart cart : carts) {
            addCollect(cart);
            deleteCart(String.valueOf(cart.getSkuId()));
        }
    }

}
